package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.item.bo.SpuBO;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import com.leyou.item.mapper.StockMapper;
import com.leyou.item.pojo.*;
import com.leyou.pojo.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Author: taft
 * @Date: 2018-9-29 16:42
 */
@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private StockMapper stockMapper;


    @Autowired
    private AmqpTemplate amqpTemplate;

    Logger logger = LoggerFactory.getLogger(GoodsService.class);

    public PageResult<SpuBO> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {

        PageHelper.startPage(page, rows);

        Example example = new Example(Spu.class);

        Example.Criteria criteria = example.createCriteria();

        if (saleable != null) {
            criteria.andEqualTo("saleable", saleable);
        }

        if (StringUtils.isNotBlank(key)) {

            criteria.andLike("title", "%" + key + "%");
        }

        //如果返回值类型不转则一定要使用PageInfo,才会统计总数
        Page<Spu> spusInfo = (Page<Spu>) spuMapper.selectByExample(example);


        List<SpuBO> spuBOS = new ArrayList<>();

        for (Spu spu : spusInfo) {
            //把直接查到的spu属性值转到spuBo中
            SpuBO spuBO = new SpuBO();
            BeanUtils.copyProperties(spu, spuBO);

            //由于spu中缺bname以及cname，所以要单独查询赋值
            //根据品牌的id查询品牌的名称
            Brand brand = brandService.queryBrandById(spu.getBrandId());

            spuBO.setBname(brand.getName());

            // 2、查询spu的商品分类名称,要查三级分类

            //根据分类的id，查询分类的名称
            List<String> names = this.categoryService.queryNamesByIds(
                    Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            // 将分类名称拼接后存入
            spuBO.setCname(StringUtils.join(names, "/"));


            spuBOS.add(spuBO);


        }


        if (null != spuBOS) {

            PageResult<SpuBO> spuBOPageResult = new PageResult<>();
            spuBOPageResult.setTotal(spusInfo.getTotal());
            spuBOPageResult.setItems(spuBOS);
            return spuBOPageResult;
        }

        return null;
    }

    @Transactional
    public void save(SpuBO spuBO) {

        Spu spu = new Spu();

        BeanUtils.copyProperties(spuBO, spu);

        //spu非输入性特征值
        spu.setSaleable(true);
        spu.setValid(true);
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(spu.getCreateTime());


        this.spuMapper.insert(spu);

        SpuDetail spuDetail = spuBO.getSpuDetail();

        spuDetail.setSpuId(spu.getId());

        this.spuDetailMapper.insert(spuDetail);

        List<Sku> skus = spuBO.getSkus();

        skus.forEach(sku -> {
            sku.setSpuId(spu.getId());
            sku.setCreateTime(spu.getCreateTime());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insert(sku);

            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insert(stock);

        });

       sendMessage(spu.getId(),"insert");
    }

    public SpuDetail querySpuDetailById(Long id) {
        return this.spuDetailMapper.selectByPrimaryKey(id);
    }

    public List<Sku> querySkuBySpuId(Long id) {
        Sku record = new Sku();
        record.setSpuId(id);

        List<Sku> skus = this.skuMapper.select(record);
        for (Sku sku : skus) {
            // 同时查询出库存
            sku.setStock(this.stockMapper.selectByPrimaryKey(sku.getId()).getStock());
        }
        return skus;
    }

    public void updateGoods(SpuBO spuBO) {
        Spu spu = new Spu();

        BeanUtils.copyProperties(spuBO, spu);

        //spu非输入性特征值
        spu.setSaleable(true);
        spu.setValid(true);
        spu.setCreateTime(new Date());
        spu.setLastUpdateTime(spu.getCreateTime());


        this.spuMapper.updateByPrimaryKeySelective(spu);

        SpuDetail spuDetail = spuBO.getSpuDetail();

        spuDetail.setSpuId(spu.getId());

        this.spuDetailMapper.updateByPrimaryKeySelective(spuDetail);

        List<Sku> skus = spuBO.getSkus();
        //TODO 去把之前sku全部删除


        /**
         * 修改sku是直接具备id的，所以可以这么做，如果本次来了4(null,a,null,c)个id，数据库中有5（a,b,c,d,e）个id
         *
         * 要做这4个id和这5个id的对比，
         *
         * 把原来有的id但是现在没有的，这波进行修改，改成无效的
         *
         * 把有id的这几个进行修改
         *
         * 没有id的做新增
         *
         *
         */

        skus.forEach(sku -> {
            sku.setSpuId(spu.getId());
            sku.setCreateTime(spu.getCreateTime());
            sku.setLastUpdateTime(sku.getCreateTime());
            this.skuMapper.insert(sku);

            Stock stock = new Stock();
            stock.setSkuId(sku.getId());
            stock.setStock(sku.getStock());
            this.stockMapper.insert(stock);

        });
        System.out.println("spu = " + spuBO);

        sendMessage(spu.getId(),"update");
    }

    public Spu querySpuById(Long id) {
        return this.spuMapper.selectByPrimaryKey(id);
    }


    private void sendMessage(Long id, String type){
        // 发送消息
        try {
            this.amqpTemplate.convertAndSend("item." + type, id);
        } catch (Exception e) {
            logger.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }
}
